Page({
  data: {
    id: '',
    name: '',
    phone: '',
    postcode: '',
    regionArray: [],
    regionStr: '',
    detail: ''
  },

  onLoad(options) {
    const { id } = options
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    const address = prevPage.data.addresses.find(item => item.id === parseInt(id))
    
    if (address) {
      this.setData({
        id: address.id,
        name: address.name,
        phone: address.phone,
        postcode: address.postcode,  // 添加邮政编码
        ...this.parseAddress(address.address)
      })
    }
  },

  parseAddress(address) {
    // 假设地址格式为："省份 城市 区县 详细地址"
    const addressParts = address.split(' ')
    const regionStr = addressParts.slice(0, 3).join(' ') // 取前三部分作为地区
    const detail = addressParts.slice(3).join(' ')       // 剩余部分作为详细地址
    
    return {
      regionStr: regionStr,
      detail: detail,
      regionArray: regionStr.split(' ') // 添加regionArray用于picker组件
    }
  },
  handleRegionChange(e) {
    const regionArray = e.detail.value
    this.setData({
      regionArray: regionArray,
      regionStr: regionArray.join(' ')
    })
  },

  saveAddress() {
    const { id, name, phone, postcode, regionStr, detail } = this.data

    if (!name || !phone || !regionStr || !detail) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }

    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    
    // 更新地址列表
    const newAddresses = prevPage.data.addresses.map(item => {
      if (item.id === id) {
        return {
          ...item,
          name,
          phone,
          address: `${regionStr} ${detail}`,
          postcode
        }
      }
      return item
    })
    
    prevPage.setData({
      addresses: newAddresses
    })

    wx.navigateBack()
  }
})